<template>
  <div>
    <ul class="list">
      <li
        v-for="item in letters"
        :key="item"
        @touchstart.prevent="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd"
        @click="handleClick"
        :ref="item"
        class="item"
      >
        {{item}}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'Alphabet',
  props: {
    cities: Object
  },
  computed: {
    letters() {
      const letters = []
      for (let item in this.cities) {
        letters.push(item)
      }
      return letters
    }
  },
  data() {
    return {
      touchState: false,
      startY: 0,
      timer: null,
      activeLetter: null
    }
  },
  updated() {
    // this.zoomAlp('E')
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleTouchStart() {
      this.touchState = true
    },
    handleTouchMove(e) {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      // 节流处理
      setTimeout(() => {
        if (this.touchState) {
          const touchY = e.touches[0].clientY - 79
          const index = Math.floor((touchY - this.startY) / 20)
          if (index >= 0 && this.letters.length) {
            this.activeLetter = this.letters[index]
            this.zoomAlp()
            this.$emit('change', this.letters[index])
          }
        }
      }, 16)
    },
    handleTouchEnd() {
      this.touchState = false
      this.clearActive(this.activeLetter)
      this.activeLetter = null
    },
    handleClick(e) {
      this.$emit('change', e.target.innerText)
    },
    // 添加 active 样式
    zoomAlp() {
      this.clearActive(this.activeLetter)
      this.$refs[this.activeLetter][0].classList.add('active')
    },
    // 清除 active样式
    clearActive() {
      this.letters.forEach(x => {
        this.$refs[x][0].classList.remove('active')
      })
    }
  },
  mounted() {

  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .list
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute
    top: 1.58rem
    right: 0
    bottom: 0
    width: .4rem

    .item
      line-height: .4rem
      text-align: center
      color: $bgColor
      width 20px
      transition transform .3s

      &.active
        transform: translate(-65px) scale(2)
        background-color rgba(0, 0, 0, .3)
        color #fff
        border-radius 50%
</style>
